package edu.sctu.yueding.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.HashMap;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.ChooseLineListViewAdapter;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.Route;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.L;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;


/**
 * Created by Administrator on 2016/8/15.
 */
public class ChooseLineActivity extends BaseActivity {
    private ExpandableListView contentListView;
    private ImageView backButton;
    private Button chooseLineButton;
    private String matchId;
    private SharePreference sharePreference;
    private long routeId;
    private String content = null;
    private JsonBaseListBean<Route> roteBean;
//    private int lineMembersCount;

    private int lineMembersMinCount;
    private int lineMembersMaxCount;

    private ProgressDialog progressDialog;
    private ProgressUtil progressUtil;

    private InputTeamName inputTeamNamePupWindow;


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_chooseline);
        initSystemBar(this, 0);
        initView();
        contentListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                //TODO:item点击事件 赋值
                routeId = roteBean.getData().get(groupPosition).getRouteList().get(childPosition).getId();


                lineMembersMinCount = roteBean.getData().get(groupPosition).getRouteList().get(childPosition).getMinCount();
                lineMembersMaxCount = roteBean.getData().get(groupPosition).getRouteList().get(childPosition).getMaxCount();

//                Log.e("lineMembersMinCount",lineMembersMinCount+"");
//
//                Log.e("lineMembersMaxCount",lineMembersMaxCount+"");

                content = roteBean.getData().get(groupPosition).getRouteList().get(childPosition).getIntroduction().toString();

                return true;
            }
        });

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
    }

    private void initView() {

        sharePreference = SharePreference.getInstance(this);
        matchId = sharePreference.getString(CacheConfig.CACHE_MATCH_ID);
        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.getChooseRoute(matchId),
                listener, errorListener, (long) 500);

        contentListView = (ExpandableListView) findViewById(R.id.activity_activity_chooseLine_expandableListView);

        chooseLineButton = (Button) findViewById(R.id.activity_choose_line_next_button);


        progressUtil = ProgressUtil.getInstance(ChooseLineActivity.this, "");

        chooseLineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:点击完成  缓存id

                if (content == null) {
                    Toast.makeText(ChooseLineActivity.this, "请选择一条路线", Toast.LENGTH_SHORT).show();
                } else {
                    progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, false);
                    sharePreference.setCache(CacheConfig.CACHE_ROUTE_ID, routeId);
                    createTeamId();
                }

            }
        });

        backButton = (ImageView) findViewById(R.id.activity_activity_chooseLine_return);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeCache();
                finish();
            }
        });
    }

    private void createTeamId() {
        Response.Listener<String> createTeamListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                Log.e("createTeamJson", json);
                JsonBaseBeen<Integer> teamCreateBean = JSON.parseObject(json, new TypeReference<JsonBaseBeen<Integer>>(){}.getType());

                if (teamCreateBean.getMeta().code == 200){

                    int teamId = teamCreateBean.getData();
                    sharePreference.setCache(CacheConfig.CACHE_TEAM_ID, teamId);

                    //传入　当前线路人数

                    SharePreference.getInstance(ChooseLineActivity.this).setCache(CacheConfig.CACHE_LINE_MIN_NUMBER, lineMembersMinCount);
                    SharePreference.getInstance(ChooseLineActivity.this).setCache(CacheConfig.CACHE_LINE_MAX_NUMBER, lineMembersMaxCount);

                    initPopupWindow(teamId);

                }else if (teamCreateBean.getMeta().code == 40000700){
                    Toast.makeText(ChooseLineActivity.this, "您不需要再次报名！", Toast.LENGTH_SHORT).show();

                }
                progressUtil.dismiss(progressDialog);
            }
        };

        Response.ErrorListener createTeamErrorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressUtil.dismiss(progressDialog);
                Toast.makeText(ChooseLineActivity.this, "网络出了些小问题", Toast.LENGTH_SHORT).show();
                Log.e("Failed ", "create failed");
            }
        };

        HashMap<String, String> map = new HashMap<>();
        String matchId = sharePreference.getString(CacheConfig.CACHE_MATCH_ID);
        map.put("matchId", String.valueOf(matchId));
        String token = sharePreference.getString(CacheConfig.CACHE_TOKEN);
        Log.e("token", token);
        GetVolleyHttp.getInstance(ChooseLineActivity.this).getStringPOSTJsonData(
                URLConfig.URL_CREATE_TEAM, map, createTeamListener, createTeamErrorListener, URLConfig.BEAREAR + token);
    }

    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {
            Log.d("json", json);

            chooseLineButton.setVisibility(View.VISIBLE);

            roteBean = JSON.parseObject(json, new TypeReference<JsonBaseListBean<Route>>() {
            }.getType());

            contentListView.setAdapter(new ChooseLineListViewAdapter(ChooseLineActivity.this, roteBean.getData()));

        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(ChooseLineActivity.this, "网络出了些小问题", Toast.LENGTH_SHORT)
                    .show();
        }
    };

    private void removeCache() {
        sharePreference = SharePreference.getInstance(this);
        sharePreference.removeOneCache(CacheConfig.CACHE_ROUTE_ID);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 初始化PopupWindow
     */
    private void initPopupWindow(int teamId) {
        View view = LayoutInflater.from(this).inflate(R.layout.input_team_name, null);
        lightOff();
        inputTeamNamePupWindow = new InputTeamName(this,
                view,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                teamId);

        inputTeamNamePupWindow.setAnimationStyle(R.style.input_team_name_popupwindow_anim);
        inputTeamNamePupWindow.showAtLocation(view, Gravity.CENTER, 20, 0);


        inputTeamNamePupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();

            }
        });
    }


    class InputTeamName extends PopupWindow{
        private View mConvertView;
        private Button mButton;

        private EditText mEditText;

        private Context context;
        private long teamId;

        public InputTeamName(Context context, View mConvertView, int mWidth, int mHeight, long teamId) {

            this.mConvertView = mConvertView;
            setContentView(mConvertView);
            setWidth(mWidth);
            setHeight(500);
            this.context = context;
            this.teamId = teamId;

            setFocusable(true);//设置可触摸
            setTouchable(true);//
            setOutsideTouchable(true);//设置外部可触摸

            setBackgroundDrawable(new BitmapDrawable());//点击外面消失

            setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {//判断动作是点击在外部
                        dismiss();//消失
                        return true;
                    }
                    return false;
                }
            });

            initView();
        }

        private void initView() {

            mEditText = (EditText) mConvertView.findViewById(R.id.id_input_team_name_edit_text);
            mButton = (Button) mConvertView.findViewById(R.id.id_input_team_name_btn);


            mButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, false);

                    String teamName = mEditText.getText().toString();
                    if (!teamName.equals("") && teamName != null){
                        postTeamName(teamName);
                    }else {
                        progressUtil.dismiss(progressDialog);
                        Toast.makeText(context,"队伍名字不能空", Toast.LENGTH_SHORT).show();
                    }

                }
            });

        }

        private void postTeamName(String teamName){
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name", teamName);
            GetVolleyHttp.getInstance((Activity) context).getStringPOSTJsonData(URLConfig.URL_POST_TEAM_NAME(teamId), map, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    L.d("teamNeam", response);
                    JSONObject jsonObject = JSON.parseObject(response);
                    JSONObject meta  = jsonObject.getJSONObject("meta");
                    int code = meta.getIntValue("code");
                    L.d("code",code+"");
                    progressUtil.dismiss(progressDialog);
                    if (code == 200){
                        inputTeamNamePupWindow.dismiss();
                        JumpUtils.jumpActivity(ChooseLineActivity.this, SignUpMyTeamActivity.class);
                        finish();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressUtil.dismiss(progressDialog);
                }
            });
        }
    }


    /**
     * 内容区域变亮
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 1.0f;
        this.getWindow().setAttributes(lp);
    }

    /**
     * 内容区域变暗
     */
    private void lightOff() {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = .3f;
        this.getWindow().setAttributes(lp);
    }
}
